from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Enum, Date, Float
from sqlalchemy.orm import relationship
from database import Base
from datetime import datetime, timezone
import enum, uuid
import random


class UserType(enum.Enum):
    free = "free"
    month = "month"
    season = "season"
    year = "year"
    admin = "admin"


class ActivationMethod(enum.Enum):
    wechat = "wechat"
    alipay = "alipay"
    kami = "kami"
    manual = "manual"
    other = "other"


class Users(Base):
    __tablename__ = "users"
    user_id = Column(Integer, primary_key=True, index=True)
    username = Column(String, unique=True, nullable=False)
    password = Column(String, nullable=False)
    # 基础状态
    status = Column(Integer, default=1)  # 1正常 0禁用
    user_type = Column(Enum(UserType), default=UserType.free)
    created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))  # 注册时间
    # API 认证
    client_id = Column(String(9), unique=True, default=lambda: ''.join([str(random.randint(0, 9)) for _ in range(9)]))
    client_secret = Column(String, default='')

    # 开通会员字段
    activated_at = Column(DateTime, nullable=True)  # 开卡时间
    vip_status = Column(Integer, default=0)
    vip_expire = Column(DateTime, nullable=True)  # 会员到期时间
    activation_method = Column(Enum(ActivationMethod), nullable=True)  # 激活方式

    licenses = relationship("Licenses", back_populates="user")
    calls = relationship("ApiCalls", back_populates="user")
    call_logs = relationship("ApiCallLogs", back_populates="user")
    orders = relationship("Orders", back_populates="user")
    used_kami = relationship("Kami", back_populates="user")


class OrderStatus(enum.Enum):
    pending = "pending"      # 待支付
    paid = "paid"           # 已支付
    expired = "expired"     # 支付失败


class Orders(Base):
    __tablename__ = "orders"
    order_id = Column(String, primary_key=True, index=True)  # 支持 UUID 字符串
    user_id = Column(Integer, ForeignKey("users.user_id"))
    vip_type = Column(Enum(UserType, native_enum=False))
    pay_type = Column(String)
    amount = Column(Float)
    status = Column(Enum(OrderStatus, native_enum=False), default=OrderStatus.pending)
    created_at = Column(DateTime, default=lambda: datetime.now())
    paid_at = Column(DateTime, nullable=True)
    # 复核字段：是否已复核
    is_verified = Column(Integer, default=0, comment="订单复核（1=已复核、0=未复核）")
    remark = Column(String, default="", comment="备注")

    user = relationship("Users", back_populates="orders")


class Kami(Base):
    __tablename__ = "kami"
    id = Column(Integer, primary_key=True)
    code = Column(String, unique=True, nullable=False)  # 卡密
    vip_type = Column(Enum(UserType), nullable=False)  # 激活的会员等级
    days = Column(Integer, default=3)  # 卡密对应有效天数
    is_used = Column(Integer, default=0)  # 是否使用（0=未使用, 1=已使用）
    created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))  # 卡密生成时间
    used_at = Column(DateTime, nullable=True)  # 使用时间
    user_id = Column(Integer, ForeignKey("users.user_id"), nullable=True)  # 使用卡密的用户ID
    remark = Column(String, default="", comment="备注")

    user = relationship("Users", back_populates="used_kami")


class Licenses(Base):
    __tablename__ = "licenses"
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.user_id"))
    license_type = Column(Enum(UserType))
    start_date = Column(Date)
    end_date = Column(Date)

    user = relationship("Users", back_populates="licenses")


class ApiCalls(Base):
    __tablename__ = "api_calls"
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.user_id"))
    call_date = Column(Date, default=datetime.now().date)
    call_count = Column(Integer, default=0)

    user = relationship("Users", back_populates="calls")


class ApiCallLogs(Base):
    __tablename__ = "api_call_logs"
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.user_id"))
    url = Column(String)
    created_at = Column(DateTime, default=datetime.now)

    user = relationship("Users", back_populates="call_logs")


class Config(Base):
    __tablename__ = "config"
    id = Column(Integer, primary_key=True, index=True)
    field = Column(String(50), unique=True, nullable=False, comment="配置字段名")
    title = Column(String(100), nullable=False, comment="配置名称")
    tip = Column(String(255), default="", comment="填写提示")
    data = Column(String, default="", comment="配置内容")
    # typeid直接用整数：1=系统基础设置，2=调用次数限制，3=会员价格，4=支付设置
    typeid = Column(Integer, nullable=False, comment="配置分组ID")
    orders = Column(Integer, default=0, comment="同分组内的排序号")
    status = Column(Integer, default=1, comment="配置状态")